/**
 * Project Name:jiuselu-parent
 * File Name:UserFareController.java
 * Package Name:com.fxp.project.jiuselu.web.business.v1.controller.user
 * Date:2021年11月22日 11:03
 * Copyright (c) 2021, Kai.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.web.business.v1.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.commons.exceptions.ParamException;
import com.fxp.project.jiuselu.commons.utils.CommonUtil;
import com.fxp.project.jiuselu.web.base.controller.BaseController;
import com.fxp.project.jiuselu.web.base.request.ReqBase;
import com.fxp.project.jiuselu.web.business.v1.request.base.ReqBasePage;
import com.fxp.project.jiuselu.web.business.v1.request.user.ReqUserFareSetting;
import com.fxp.project.jiuselu.web.constant.Constants;
import com.fxp.project.jiuselu.web.domain.CommonPage;
import com.fxp.project.jiuselu.web.domain.CommonResult;
import com.fxp.project.jiuselu.web.models.fare.entity.JslUserFareApplied;
import com.fxp.project.jiuselu.web.models.fare.entity.JslUserFareOrderApply;
import com.fxp.project.jiuselu.web.models.fare.service.IJslUserFareAppliedService;
import com.fxp.project.jiuselu.web.models.fare.service.IJslUserFareOrderApplyService;
import com.fxp.project.jiuselu.web.models.user.entity.JslUserExtend;
import com.fxp.project.jiuselu.web.models.user.service.IJslUserExtendService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * ClassName:UserFareController<br/>
 * Function: 用户发票设置<br/>
 * Date:2021年11月22日 11:03<br/>
 *
 * @author Kai.Wang
 * @version 1.0.0
 * @see
 * @since JDK 8
 */
@RestController
@RequestMapping("/v1/user/fare")
public class UserFareController extends BaseController {

    @Autowired
    IJslUserExtendService jslUserExtendService;
    @Autowired
    IJslUserFareAppliedService jslUserFareAppliedService;
    @Autowired
    IJslUserFareOrderApplyService jslUserFareOrderApplyService;

    /**
     * history: 开票历史<br/>
     *
     * @param reqBasePage
     * @param result
     * @return
     * @author Jason.Wang
     * @date 2021/11/24 11:51 下午
     */
    @PostMapping("history")
    @CrossOrigin
    public CommonResult history(@RequestBody @Validated ReqBasePage reqBasePage, BindingResult result) {
        super.checkBindResult(result);
//        LocalDateTime currentDate = super.setPageQueryTag(Constants.USER_FARE_HISTORY_LIST_CODE, reqBasePage.getPage(), super.getCurrentUserInfo().getUserId());
        PageInfo<?> pageInfo = jslUserFareAppliedService.selectJslUserFareAppliedListById(reqBasePage.getPage(), reqBasePage.getSize(), LocalDateTime.now(), super.getCurrentUserInfo().getUserId());
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * detail: 当前用户的发票设定<br/>
     *
     * @return
     * @author Kai.Wang
     * @date 2021/11/22 11:32
     */
    @PostMapping("detail")
    @CrossOrigin
    public CommonResult detail(@RequestBody @Validated ReqBasePage reqBasePage, BindingResult result) {
        super.checkBindResult(result);
        List<JslUserExtend> oldJslUserExtend = jslUserExtendService.selectJslUserExtendByUserId(super.getCurrentUserInfo().getUserId());
        return CommonResult.success(oldJslUserExtend);
    }

    /**
     * detail: 当前用户的发票设定<br/>
     *
     * @return
     * @author Kai.Wang
     * @date 2021/11/22 11:32
     */
    @PostMapping("quereyById")
    @CrossOrigin
    public CommonResult quereyById(@RequestBody @Validated ReqUserFareSetting reqUserFareSetting, BindingResult result) {
        super.checkBindResult(result);
        JslUserExtend oldJslUserExtend = jslUserExtendService.getById(reqUserFareSetting.getId());
        return CommonResult.success(oldJslUserExtend);
    }

    /**
     * detail: 当前用户的发票设定<br/>
     *
     * @return
     * @author Kai.Wang
     * @date 2021/11/22 11:32
     */
    @PostMapping("updateById")
    @CrossOrigin
    public CommonResult updateById(@RequestBody @Validated ReqUserFareSetting reqUserFareSetting, BindingResult result) {
        super.checkBindResult(result);
        JslUserExtend jslUserExtend = new JslUserExtend();
        jslUserExtend.setState(0);
        jslUserExtendService.update(jslUserExtend, new QueryWrapper<JslUserExtend>().eq("user_id", super.getCurrentUserInfo().getUserId()));
        jslUserExtend.setState(1);
        jslUserExtend.setId(reqUserFareSetting.getId());
        return CommonResult.success(jslUserExtendService.updateById(jslUserExtend));
    }

    /**
     * setting: 用户发票设置<br/>
     *
     * @param reqUserFareSetting
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/22 11:09
     */
    @PostMapping("setting")
    @CrossOrigin
    public CommonResult setting(@RequestBody @Validated ReqUserFareSetting reqUserFareSetting, BindingResult result) {
        super.checkBindResult(result);
        // 检查发票必填信息
        checkSubmitData(reqUserFareSetting);
        // 查询数据库中原始的发票信息
        JslUserExtend jslUserExtend = new JslUserExtend();
        jslUserExtend.setUserId(super.getCurrentUserInfo().getUserId());
        jslUserExtend.setFareType(reqUserFareSetting.getFareType());
        jslUserExtend.setInvoiceTitle(reqUserFareSetting.getInvoiceTitle());
        jslUserExtend.setTaxpayer(reqUserFareSetting.getTaxpayer());
        jslUserExtend.setAddress(reqUserFareSetting.getAddress());
        jslUserExtend.setPhone(reqUserFareSetting.getPhone());
        jslUserExtend.setBank(reqUserFareSetting.getBank());
        jslUserExtend.setBankAccount(reqUserFareSetting.getBankAccount());
        jslUserExtend.setRealName(reqUserFareSetting.getRealName());
        jslUserExtend.setIdCard(reqUserFareSetting.getIdCard());
        jslUserExtend.setEmail(reqUserFareSetting.getEmail());
        if (null != reqUserFareSetting.getId()) {
            jslUserExtend.setId(reqUserFareSetting.getId());
            return CommonResult.success(jslUserExtendService.updateById(jslUserExtend));
        } else {
            return CommonResult.success(jslUserExtendService.save(jslUserExtend));
        }
    }

    /**
     * setting: 用户申请开票<br/>
     *
     * @param
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/22 11:09
     */
    @PostMapping("seve")
    @CrossOrigin
    public CommonResult setting(@RequestBody @Validated JslUserFareApplied jslUserFareApplied, BindingResult result) {
        super.checkBindResult(result);
        JslUserExtend jslUserExtend = null;
        if (Optional.ofNullable(jslUserFareApplied.getFareId()).isPresent()) {
            jslUserExtend = jslUserExtendService.getById(jslUserFareApplied.getFareId());
            jslUserFareApplied.setExtendId(jslUserFareApplied.getFareId());
            jslUserFareApplied.setFareId(null);
        }
        if (Optional.ofNullable(jslUserFareApplied.getExtendId()).isPresent()) {
            jslUserExtend = jslUserExtendService.getById(jslUserFareApplied.getExtendId());
        }
        jslUserFareApplied.setUserId(super.getCurrentUserInfo().getUserId());
        jslUserFareApplied.setFareType(jslUserExtend.getFareType());
        jslUserFareApplied.setInvoiceTitle(jslUserExtend.getInvoiceTitle());
        jslUserFareApplied.setTaxpayer(jslUserExtend.getTaxpayer());
        jslUserFareApplied.setAddress(jslUserExtend.getAddress());
        jslUserFareApplied.setPhone(jslUserExtend.getPhone());
        jslUserFareApplied.setBank(jslUserExtend.getBank());
        jslUserFareApplied.setBankAccount(jslUserExtend.getBankAccount());
        jslUserFareApplied.setRealName(jslUserExtend.getRealName());
        jslUserFareApplied.setIdCard(jslUserExtend.getIdCard());
        jslUserFareApplied.setEmail(jslUserExtend.getEmail());
        jslUserFareApplied.setCreateTime(LocalDateTime.now());
        //防止插入同一条订单多次开票
        String orderIds = jslUserFareApplied.getOrderIds();
        String substring = orderIds.substring(0, orderIds.length() - 1);
        String[] ids=substring.split(",");
        for (String orderId : ids){
            System.out.println("分割后的orderId--->"+orderId);
            JslUserFareOrderApply jslUserFareOrderApply = jslUserFareOrderApplyService.selectApplyByOrderId(orderId);
            if(jslUserFareOrderApply !=null){
                throw new JiuLuException(ConstantCode.SYSTEM_EXCEPTION.getCode(),"该订单已申请过开票,请勿多次开票");
            }
        }



        if (jslUserFareAppliedService.save(jslUserFareApplied)) {
            return CommonResult.success(jslUserFareApplied);
        } else {
            return CommonResult.success(jslUserFareApplied);
        }
    }

    /**
     * checkSubmitData: 检查当前用户添加时候的设定<br/>
     *
     * @param reqUserFareSetting
     * @author Kai.Wang
     * @date 2021/11/22 11:16
     */
    private void checkSubmitData(ReqUserFareSetting reqUserFareSetting) {
        if (reqUserFareSetting.getFareType() == 1) {
            if (StringUtils.isBlank(reqUserFareSetting.getRealName())) {
                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "用户的真实姓名不能为空");
            }
//            if (StringUtils.isBlank(reqUserFareSetting.getIdCard())) {
//                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "用户身份证号不能为空");
//            }
//            if (StringUtils.isBlank(reqUserFareSetting.getEmail())) {
//                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "电子邮箱地址不能为空");
//            }
        } else {
            // 当前配置为公司的设置时候
            if (StringUtils.isBlank(reqUserFareSetting.getInvoiceTitle())) {
                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "单位名称不能为空");
            }
            if (StringUtils.isBlank(reqUserFareSetting.getTaxpayer())) {
                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "纳税人识别号不能为空");
            }
            if (StringUtils.isBlank(reqUserFareSetting.getAddress())) {
                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "单位地址不能为空");
            }
            if (StringUtils.isBlank(reqUserFareSetting.getPhone())) {
                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "电话号码不能为空");
            }
            if (StringUtils.isBlank(reqUserFareSetting.getBank())) {
                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "开户行名称不能为空");
            }
            if (StringUtils.isBlank(reqUserFareSetting.getBankAccount())) {
                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "银行账户号码不能为空");
            }
//            if (StringUtils.isBlank(reqUserFareSetting.getEmail())) {
//                throw new ParamException(ConstantCode.PARAM_EXCEPTION.getCode(), "电子邮箱地址不能为空");
//            }
        }
    }

}
